﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using FCModel;
using FCDAL;
using System.Data;
using System.Data.OleDb;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;
using MiscLib;

namespace FCBLL
{
    public class TableFormatBLL : IFormatBLL
    {
        IList<string> Value_Strs_List = new List<string>();
        //增加标题行和值行的定义在testype
        int iHeadIndex = 0;
        int iValueIndex = 1;
        protected bas_TestType basTestType = new bas_TestType();
        //protected bas_TestParamDao basTestParamDataTable = new bas_TestParamDao();
        public void Process_File(FileInfo fi)
        {
            Value_Strs_List = File.ReadAllLines(fi.FullName).ToList<string>();
        }

        public IList<ParameterDao> AnalysisFile(string[] arrSourceFile, string fileType)
        {
            //初始化ValueIndex和HeadIndex
            bas_TestType btt = CommonBLL.getValueIndexAndHeadIndex(fileType);
            iHeadIndex = string.IsNullOrWhiteSpace(btt.HeadIndex.ToString()) ? iHeadIndex : (Int32)btt.HeadIndex;
            iValueIndex = string.IsNullOrWhiteSpace(btt.ValueIndex.ToString()) ? iValueIndex : (Int32)btt.ValueIndex;
            //TestparamDAL tpDAL = new TestparamDAL();
            IList<ParameterDao> listSSD = new List<ParameterDao>();
            //12个
            IQueryable<bas_Testparam> listBT = new BaseRepositoryDAL<bas_Testparam>().LoadEntities(p => p.testType.Equals(fileType, StringComparison.OrdinalIgnoreCase));

            string sequence = new BaseRepositoryDAL<bas_TestType>().LoadEntities(p => p.testType.Equals(fileType, StringComparison.OrdinalIgnoreCase)).FirstOrDefault().dataFieldIndex;
            //tpDAL.GetTestParamBytestType(fileType);
            int iSeqNo = 1;
            string rowData;
            for (int i = iValueIndex; i < arrSourceFile.Length; i++)
            {
                rowData = arrSourceFile[i];
                if (string.IsNullOrWhiteSpace(rowData.Trim()))
                {
                    continue;
                }
                ParameterDao pd = new ParameterDao();
                string[] temArrData = rowData.Split(',');
                pd.SeqNo = iSeqNo.ToString();

                //将数据库中的转换成程序需要的结构
                foreach (bas_Testparam bt in listBT.Where(p => string.IsNullOrWhiteSpace(p.Express)))
                {
                    if (sequence != "排序查找" && !string.IsNullOrWhiteSpace(bt.longName))
                    {
                        bt.seqNo = Get_Parameter_Position(arrSourceFile[iHeadIndex].ToString(), bt.longName);
                    }
                    Parameter ss = new Parameter();//math.Absfloat.Parse(temArrData[bt.seqNo])
                    ss.ParameterName = bt.testParam;
                    ss.ParameterValue = (float)Math.Abs(Math.Round(float.Parse(temArrData[bt.seqNo].Trim('\0')), 5, MidpointRounding.AwayFromZero));
                    pd.listSSD.Add(ss);
                }

                foreach (bas_Testparam bt in listBT.Where(p => !string.IsNullOrWhiteSpace(p.Express)))
                {
                    string exp = bt.Express;
                    float fttmp = 0;
                    foreach (Parameter sstmp in pd.listSSD)
                    {
                        exp = exp.Replace(sstmp.ParameterName, sstmp.ParameterValue.ToString());
                    }
                    try
                    {
                        string rlt = DynamicExpress.GetValue(exp);
                        fttmp = (float)Math.Abs(Math.Round(float.Parse(rlt), 5, MidpointRounding.AwayFromZero));// float.Parse(rlt);
                    }
                    catch { }
                    Parameter ss = new Parameter();
                    ss.ParameterName = bt.testParam;
                    ss.ParameterValue = fttmp;
                    pd.listSSD.Add(ss);
                }
                iSeqNo++;
                listSSD.Add(pd);
            }
            return listSSD;
        }

        /// <summary>
        /// 按列名查找序列号
        /// </summary>
        /// <param name="str_row">列名集合</param>
        /// <param name="search_parameter">查找的列名</param>
        /// <returns></returns>
        protected virtual int Get_Parameter_Position(string str_row, string search_parameter)
        {
            int pos = -1;
            string[] strs = str_row.Trim().Split(',');

            for (int k = 0; k < strs.Length; k++)
            {
                if (strs[k].Trim().Equals(search_parameter, StringComparison.OrdinalIgnoreCase))
                {
                    pos = k;
                    break;
                }
            }
            return pos;
        }



        //获取数据库定义处理文件参数的信息
        //public   IList<ParameterDao> BeltonLaserProcessFile(string[] arrSourceFile, string fileType)
        //{
        //    //初始化ValueIndex和HeadIndex
        //    getValueIndexAndHeadIndex(fileType);
        //    TestparamDAL tpDAL = new TestparamDAL();
        //    IList<ParameterDao> listSSD = new List<ParameterDao>();
        //    //18个
        //    IList<bas_Testparam> listBT = tpDAL.GetTestParamBytestType(fileType);
        //    int iSeqNo = 1;
        //    string rowData;
        //    for (int i = iValueIndex; i < arrSourceFile.Length; i++)
        //    {
        //        rowData = arrSourceFile[i];
        //        if (string.IsNullOrWhiteSpace(rowData.Trim())) {
        //            continue;
        //        }
        //        ParameterDao btpd = new ParameterDao();
        //        string[] temArrData = rowData.Split(',');

        //        btpd.SeqNo = iSeqNo.ToString();
        //        foreach (bas_Testparam bt in listBT)
        //        {
        //            Parameter ss = new Parameter();//math.Absfloat.Parse(temArrData[bt.seqNo])
        //            ss.ParameterName = bt.testParam;
        //            ss.ParameterValue = (float)Math.Abs(Math.Round(float.Parse(temArrData[bt.seqNo]), 5, MidpointRounding.AwayFromZero));
        //            btpd.listSSD.Add(ss);
        //        }
        //        iSeqNo++;
        //        listSSD.Add(btpd);
        //    }
        //    return listSSD;
        //}

        //public   IList<ParameterDao> BeltonLaserProcessFile1(string[] arrSourceFile, string fileType)
        //{
        //    TestparamDAL tpDAL = new TestparamDAL();
        //    IList<ParameterDao> listSSD = new List<ParameterDao>();
        //    //12个
        //    IList<bas_Testparam> listBT = tpDAL.GetTestParamBytestType(fileType);
        //    int iSeqNo = 1;
        //    foreach (string rowData in arrSourceFile)
        //    {
        //        ParameterDao btpd = new ParameterDao();
        //        string[] temArrData = rowData.Split(',');
        //        if (temArrData[0].ToString().Trim() == "YR2")
        //        {
        //            btpd.SeqNo = iSeqNo.ToString();
        //            foreach (bas_Testparam bt in listBT)
        //            {
        //                Parameter ss = new Parameter();//math.Absfloat.Parse(temArrData[bt.seqNo])
        //                ss.ParameterName = bt.testParam;
        //                ss.ParameterValue = (float)Math.Abs(Math.Round(float.Parse(temArrData[bt.seqNo]), 5, MidpointRounding.AwayFromZero));
        //                btpd.listSSD.Add(ss);
        //            }
        //            iSeqNo++;
        //            listSSD.Add(btpd);
        //        }
        //    }
        //    return listSSD;
        //}

        //public   DataTable ParameterDaoToDataTable(IList<ParameterDao> listSSD, string partNo)
        //{
        //    //VPC 4D FPC Data																																		
        //    //GR#:																																					
        //    //S/N	Parameter	Nominal	Max	Min	1	2	3	4	5	6	7	8	9	10	11	12	13	14	15	16	17	18	19	20	21	22	23	24	25	26	27	28	29				
        //    DataTable dt = new DataTable();
        //    dt.Columns.Add("S/N", typeof(System.String));
        //    dt.Columns.Add("Parameter", typeof(System.String));
        //    dt.Columns.Add("Nominal", typeof(System.String));
        //    dt.Columns.Add("Max", typeof(System.String));
        //    dt.Columns.Add("Min", typeof(System.String));
        //    foreach (bas_TestParamDao ssd in listSSD)
        //    {
        //        dt.Columns.Add(ssd.SeqNo, typeof(System.String));
        //    }
        //    var vParameterName = listSSD[0].listSSD.OrderBy(x => x.ParameterSortName).Select(p => p.ParameterName).Distinct();
        //    int iRow = 0;
        //    StandardDataDAL sd = new StandardDataDAL();
        //    IList<ParameterRange> listPR = sd.GetParameterRangeByPartNo(partNo);
        //    //iqcen.ParameterRange
        //    foreach (string ParameterName in vParameterName)
        //    {
        //        DataRow dr = dt.NewRow();
        //        dr["S/N"] = (++iRow).ToString();
        //        dr["Parameter"] = ParameterName;
        //        //通过基础数据获取标准值上下限值
        //        //dr["Nominal"] = listSSD[0].listSSD.Where(p=>p.ParameterName.Equals(ParameterName, StringComparison.OrdinalIgnoreCase)).ToList<Parameter>()[0].StandardValue;
        //        //dr["Max"] = listSSD.Select(p => p.listSSD.Where(x=>x.ParameterName.Equals(ParameterName, StringComparison.OrdinalIgnoreCase)).Select(pp => pp.ParameterValue).Max()).Max();
        //        //dr["Min"] = listSSD.Select(p => p.listSSD.Where(x => x.ParameterName.Equals(ParameterName, StringComparison.OrdinalIgnoreCase)).Select(pp => pp.ParameterValue).Min()).Min();
        //        var vStandard = listPR.Where(p => p.Parameter.Equals(ParameterName, StringComparison.OrdinalIgnoreCase)).ToList<ParameterRange>();
        //        if (vStandard != null && vStandard.Count() > 0)
        //        {
        //            dr["Nominal"] = vStandard[0].Nominal;
        //            dr["Max"] = vStandard[0].Max;
        //            dr["Min"] = vStandard[0].Min;
        //        }
        //        foreach (bas_TestParamDao ssd in listSSD)
        //        {
        //            dr[ssd.SeqNo] = ssd.listSSD.Where(p => p.ParameterName.Equals(ParameterName, StringComparison.OrdinalIgnoreCase)).ToArray<Parameter>().FirstOrDefault().ParameterValue;
        //        }
        //        dt.Rows.Add(dr);
        //    }
        //    return dt;
        //}

        //private void GetTestParamAndPrd()
        //{
        //basTestType = daMes.getTestTypeData();
        //dsTestTrace.bas_TestTypeRow[] basTestTypeRows =
        //    basTestType.Where(p => p.testType.Equals(testBaseData.TestType, StringComparison.OrdinalIgnoreCase)).ToArray<dsTestTrace.bas_TestTypeRow>();
        //testBaseData.dataFieldIndex = DataFieldIndex.FIND;
        //if (basTestTypeRows != null && basTestTypeRows.Length > 0)
        //{
        //    testBaseData.dataFieldIndex =
        //        !basTestTypeRows[0].IsdataFieldIndexNull()
        //        && basTestTypeRows[0].dataFieldIndex.Equals("SEQ", StringComparison.OrdinalIgnoreCase) ? DataFieldIndex.SEQ : DataFieldIndex.FIND;
        //}
        //basTestparam = daMes.getTestParam_By_TestType(testBaseData.TestType);
        //if (basTestparam.Rows.Count == 0)
        //    throw new Exception("没有设定" + TestType + "测试类型的basTestparam测试参数");
        //}

        //获取数据库定义处理文件参数的信息->程序需要的对象
        //protected IList<bas_TestParamDao> GetTestParameterAndPrdSum(string type)
        //{
        //    IList<bas_Testparam> listTestParam = new List<bas_Testparam>();
        //    TestparamDAL td = new TestparamDAL();

        //    listTestParam = td.GetTestParamBytestType(type);


        //    foreach (dsTestTrace.bas_TestparamRow dr in basTestparam)
        //    {
        //        int iPos = -1;
        //        if (testBaseData.dataFieldIndex == DataFieldIndex.SEQ) //按定义的顺序对应字段
        //        {
        //            iPos = dr.seqNo - 1;
        //        }
        //        else if (!String.IsNullOrWhiteSpace(HeadRow))//有字段名称行才找字段的索引位置
        //        {
        //            string testParamName = dr.testParam + ((dr.IslongNameNull() || String.IsNullOrWhiteSpace(dr.longName)) ? "" : "||" + dr.longName);
        //            if (!dr.IslongNameNull() && !String.IsNullOrWhiteSpace(dr.longName))
        //                iPos = Get_Parameter_Position(HeadRow, dr.longName);
        //            if (iPos < 0)
        //                iPos = Get_Parameter_Position(HeadRow, dr.testParam);
        //            if (iPos < 0)
        //            {
        //                To_Log("系统不能定位该测试定义的采集参数(" + testParamName + "), SN: " + prdsn);
        //                continue;
        //            }
        //        }
        //        listTestPara.Add(
        //            new TestParameter()
        //            {
        //                paramName = dr.testParam,
        //                longName = dr.IslongNameNull() ? "" : dr.longName,
        //                shortName = dr.IsshortNameNull() ? "" : dr.shortName,
        //                masterField = dr.IsmasterFieldNull() ? "" : dr.masterField,
        //                valueType = tmpvalueType,
        //                minValue = tmpminValue,
        //                maxValue = tmpmaxValue,
        //                Pos = iPos,
        //                isCustReq = dr.IscustReqNull() ? false : dr.custReq,
        //            });
        //    }
        //    return listTestPara;
        //}

        

        public DataSet ExcelToDS(string Path)
        {
            //此连接可以操作.xls与.xlsx文件 (支持Excel2003 和 Excel2007 的连接字符串)  
            string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + Path + ";Extended Properties='Excel 12.0; HDR=yes; IMEX=0'";
            OleDbConnection conn = new OleDbConnection(strConn);
            conn.Open();
            string strExcel = "";
            OleDbDataAdapter myCommand = null;
            DataSet ds = null;
            strExcel = "select * from [sheet1$]";
            myCommand = new OleDbDataAdapter(strExcel, strConn);
            ds = new DataSet();
            myCommand.Fill(ds, "table1");
            //strExcel = "select * from [sheet2$]";
            //myCommand = new OleDbDataAdapter(strExcel, strConn);
            //myCommand.Fill(ds, "table2");
            conn.Close();
            conn.Dispose();
            myCommand.Dispose();
            return ds;
        }

        public string[] DataSetToStringArray(DataSet ds)
        {
            DataTable dt = ds.Tables[0];
            IList<string> stringList = new List<string>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string ArrayLine = "";
                if (string.IsNullOrWhiteSpace(dt.Rows[i][0].ToString()))
                {
                    break;
                }
                for (int j = 0; j < dt.Columns.Count; j++)
                {

                    ArrayLine += dt.Rows[i][j].ToString() + ",";
                }
                stringList.Add(ArrayLine);
            }
            return stringList.ToArray<string>();
        }


        //private void Fill_Param_Data()
        //{
        //    //    To_Log("1");
        //    if (Value_Strs_List.Count <= 0) { throw new Exception("文件无内容或格式错误！"); }
        //    //获得系统定义测试参数
        //    //     To_Log("2");
        //    //IList<TestParameter> listTestPara = GetTestParameterAndPrdSum(prdData, Value_Strs_List[iHeadIndex], prdsn_tmp);
        //    int iStartIndex = 1;
        //    //建立岛list
        //    for (; iStartIndex < Value_Strs_List.Count; iStartIndex++)
        //    {
        //        string[] strOneLineData = Value_Strs_List[iStartIndex].Split(',');
        //        for (int j = 0; j < listTestPara.Count; j++)
        //        {
        //            string StrParamName = "";//测试项名称
        //            string StrParamValue = "";//测试项的值
        //            StrParamName = listTestPara[j].paramName;
        //            if (listTestPara[j].Pos != -1 && listTestPara[j].Pos < strOneLineData.Length) //代码指定的参数
        //            {
        //                StrParamValue = strOneLineData[listTestPara[j].Pos];
        //                StrParamValue = StrParamValue.Trim().Trim(new char[] { '\0', '\n', '\r' });
        //            }
        //            else
        //            {
        //                To_Log("系统不能定位该测试定义的采集参数(" + listTestPara[j].paramName + "/" + listTestPara[j].longName
        //                    + "), SN: " + prdsn_tmp);
        //                continue;
        //            }

        //            //将结果保存到岛list
        //            arrParamValue.Add(new TestValue()
        //            {
        //                paraNo = StrParamName,
        //                paraType = valuetype,
        //                paraValue = StrParamValue,
        //                rlt = ParamRlt,
        //                ParamRange1 = listTestPara[j].minValue,
        //                ParamRange2 = listTestPara[j].maxValue,
        //                paraSpecial1 = paraSpecial1,
        //                paraSpecial2 = paraSpecial2,
        //                paraDesc = ""
        //            });                   
        //        }
        //    }
        //    testData.AddParaTestValueLst(arrParamValue);
        //    testData.AddParaTestDefectLst(arrDefectValue);
        //}
    }
}
